//
//  SelectImgShowController.m
//  WatermarkCamera
//
//  Created by zhibao on 2023/10/18.
//

#import "SelectImgShowController.h"
#import "WatermarkView.h"
#import "MyReplyController.h"
@interface SelectImgShowController ()<UIGestureRecognizerDelegate,UIDocumentInteractionControllerDelegate>{
    //图片缩放成都
    CGFloat scale;
    UIImageView *showImgView;
    UIImageView *shuiyinImgView;
    CGFloat shuiyinLastY;
    //水印列表
    WatermarkView *watermarkListView;
}
@property (nonatomic,strong)UIDocumentInteractionController *document;
@end

@implementation SelectImgShowController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = LocalizedString(@"预览");
    shuiyinLastY = -1;
    scale = MY_Screen_W / self.image.size.width;
    CGFloat imgHeight = self.image.size.height * scale;
    
    showImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, NAVIH, MY_Screen_W, imgHeight)];
    showImgView.userInteractionEnabled = YES;
    showImgView.image = self.image;
    showImgView.centerY = MY_Screen_H / 2;
    [self.view addSubview:showImgView];
    
    shuiyinImgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, showImgView.height - self.shuiyinImage.size.height - 20, self.shuiyinImage.size.width, self.shuiyinImage.size.height)];
    shuiyinImgView.userInteractionEnabled = YES;
    shuiyinImgView.image = self.shuiyinImage;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(resultShow:)];
    pan.delegate = self;
    [shuiyinImgView addGestureRecognizer:pan];
    [showImgView addSubview:shuiyinImgView];
    
    NSArray *bottomInfos = @[
        @{@"title":LocalizedString(@"水印"),@"img":@"h_yulan_shuiyin"},
        @{@"title":LocalizedString(@"保存"),@"img":@"h_yulan_baocun"},
        @{@"title":LocalizedString(@"分享"),@"img":@"h_yulan_fenxiang"},
    ];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, MY_Screen_H - 90 - SafeBottomMargin, MY_Screen_W, 90 + SafeBottomMargin)];
    [self.view addSubview:bottomView];
    
    CGFloat btnWidth = MY_Screen_W / 3;
    
    for(int i = 0; i < bottomInfos.count; i++){
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnWidth * i, 10, btnWidth, 90);
        btn.tag = 1000 + i;
        [btn setImage:[UIImage imageNamed:bottomInfos[i][@"img"]] forState:UIControlStateNormal];
        [btn setTitle:bottomInfos[i][@"title"] forState:UIControlStateNormal];
        [btn setTitleColor:MyColor(@"333333") forState:UIControlStateNormal];
        btn.titleLabel.font = MY_SCALE_RegularFONT(12);
        [btn setButtonImageAlignmentStyle:WMButtonAlignmentStyleTop imageAndLabelSpace:8];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
    }
    
    watermarkListView = [[WatermarkView alloc]initWithFrame:CGRectMake(0, MY_Screen_H, MY_Screen_W, 390)];
    watermarkListView.layer.cornerRadius = 20;
    watermarkListView.backgroundColor = UIColor.whiteColor;
    watermarkListView.hidden = YES;
    
    __weak typeof(self) weakSelf = self;
    watermarkListView.returnShuiyinBlock = ^(UIImage * _Nonnull img) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        CGFloat width = img.size.width;
        CGFloat height = img.size.height;
        strongSelf->shuiyinImgView.width = width;
        strongSelf->shuiyinImgView.height = height;
        strongSelf->shuiyinImgView.image = img;
        CGFloat tempHeight = strongSelf->showImgView.bottom - strongSelf->watermarkListView.top;
        if(tempHeight > 0){
            strongSelf->shuiyinImgView.top = strongSelf->showImgView.height - strongSelf->shuiyinImgView.height - tempHeight - 3;
        }
    };
    
    watermarkListView.closeShuiyinBlock = ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf->shuiyinLastY != -1){
            [UIView animateWithDuration:0.3 animations:^{
                strongSelf->shuiyinImgView.top = strongSelf->shuiyinLastY;
            } completion:^(BOOL finished) {
                strongSelf->shuiyinLastY = -1;
                if(strongSelf->shuiyinImgView.top < 0){
                    strongSelf->shuiyinImgView.top = 3;
                }
                if(strongSelf->shuiyinImgView.bottom > strongSelf->showImgView.height){
                    strongSelf->shuiyinImgView.top = strongSelf->showImgView.height - strongSelf->shuiyinImgView.height - 3;
                }
            }];
        }
        [UIView animateWithDuration:0.3 animations:^{
            strongSelf->watermarkListView.top = MY_Screen_H;
        } completion:^(BOOL finished) {
            strongSelf->watermarkListView.hidden = YES;
        }];
    };
    [self.view addSubview:watermarkListView];
}

-(void)btnClick:(UIButton *)sender{
    if(sender.tag == 1000){
        //水印
        if(watermarkListView.hidden){
            watermarkListView.hidden = NO;
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H - 390;
                CGFloat tempHeight = self->showImgView.bottom - self->watermarkListView.top;
                if(tempHeight > 0){
                    self->shuiyinLastY = self->shuiyinImgView.top;
                    self->shuiyinImgView.top = self->showImgView.height - self->shuiyinImgView.height - tempHeight - 3;
                }else{
                    self->shuiyinLastY = -1;
                }
                
            } completion:^(BOOL finished) {
                
            }];
            
        }else{
            if(shuiyinLastY != -1){
                shuiyinLastY = -1;
                [UIView animateWithDuration:0.3 animations:^{
                    self->shuiyinImgView.top = self->shuiyinLastY;
                } completion:^(BOOL finished) {
                    
                }];
            }
            [UIView animateWithDuration:0.3 animations:^{
                self->watermarkListView.top = MY_Screen_H;
            } completion:^(BOOL finished) {
                self->watermarkListView.hidden = YES;
            }];
        }
    }else if(sender.tag == 1001){
        if(![[UserInfoManager sharedManager] isVip]){
            [Helper alertShowWithTitle:LocalizedString(@"提示") withContent:LocalizedString(@"您不是VIP会员，请开通订阅后再使用此功能！") withSureBtnTitle:LocalizedString(@"去看看") withCancelBtnTitle:LocalizedString(@"取消") withSelect:^(NSInteger index) {
                if(index == 1){
                    MyReplyController *controller = [MyReplyController new];
                    [self.navigationController pushViewController:controller animated:YES];
                }
            }];
            return;
        }
        
        //保存
        UIImage *imageRet = [[UIImage alloc]init];
        UIGraphicsBeginImageContextWithOptions(showImgView.size,YES, 0.0);
        [showImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
        imageRet = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        PHAuthorizationStatus authStatus = PHPhotoLibrary.authorizationStatus;
        if ( authStatus == PHAuthorizationStatusNotDetermined ) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                UIImageWriteToSavedPhotosAlbum(imageRet, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            }];
        }else{
            UIImageWriteToSavedPhotosAlbum(imageRet, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        }
        
    }else if(sender.tag == 1002){
        if(![[UserInfoManager sharedManager] isVip]){
            [Helper alertShowWithTitle:LocalizedString(@"提示") withContent:LocalizedString(@"您不是VIP会员，请开通订阅后再使用此功能！") withSureBtnTitle:LocalizedString(@"去看看") withCancelBtnTitle:LocalizedString(@"取消") withSelect:^(NSInteger index) {
                if(index == 1){
                    MyReplyController *controller = [MyReplyController new];
                    [self.navigationController pushViewController:controller animated:YES];
                }
            }];
            return;
        }
        //分享
        UIImage *imageRet = [[UIImage alloc]init];
        UIGraphicsBeginImageContextWithOptions(showImgView.size,YES, 0.0);
        [showImgView.layer renderInContext:UIGraphicsGetCurrentContext()];
        imageRet = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [Helper getImgPath:imageRet finshBlock:^(int result, NSString * _Nullable path) {
            [self exportMP3:path];
        }];
    }
}
-(void)exportMP3:(NSString *)url{
    //    NSURL *URL = [NSURL URLWithString:url];
    NSURL *URL = [NSURL fileURLWithPath:url];
    _document = [UIDocumentInteractionController interactionControllerWithURL:URL];
    _document.delegate    =  (id)self;
    _document.UTI = @"水印相机";
    _document.name = @"水印相机";
    // 用户不预览文件直接分享，如图2所示
    BOOL canOpen = [self.document presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
    
    if(!canOpen) {
        NSLog(@"沒有程序可以打开选中的文件");
    }else{
        //[_document presentPreviewAnimated:YES];
    }
}

#pragma mark - ** UIDocumentInteractionController 代理方法 **
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    return self.view.frame;
}

-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController*)controller{
    //    UIView *view = [self.view viewWithTag:1234567];
    //    if(view){
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //           // UI更新代码
    //            [view removeFromSuperview];
    //        });
    //    }
    NSLog(@"dissMiss");
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
    
    
    if(error != NULL){
        [QMUITips showError:LocalizedString(@"保存图片失败")];
    }else{
        [QMUITips showSucceed:LocalizedString(@"已保存至相册")] ;
    }
}

#pragma  mark 手势代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    DLog(@"嘤嘤嘤");
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

- (void)resultShow:(UIGestureRecognizer*)ges{
    UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *)ges;
    CGRect showResultImgFrame = showImgView.frame;
    UIView *panView = recognizer.view;
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"FlyElephant---视图拖动开始");
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGPoint location = [recognizer locationInView:self.view];
        CGPoint location1 = [recognizer locationInView:panView];
        DLog(@"1===%f   2=== %f 3=== %f 4=== %f",location.y - location1.y,location.y - location1.y + panView.height,location.x - location1.x,location.x - location1.x + panView.width);
        CGPoint translation = [recognizer translationInView:self.view];
        NSLog(@"当前视图在View的位置:%@----平移位置:%@",NSStringFromCGPoint(location),NSStringFromCGPoint(translation));
        recognizer.view.center = CGPointMake(panView.center.x + translation.x,panView.center.y + translation.y);
        
        if(panView.left < 0){
            panView.left = 0;
        }
        
        if(panView.right > MY_Screen_W ){
            panView.left = MY_Screen_W - panView.width;
        }
        
        if(panView.top < 0){
            panView.top = 0;
        }
        
        if(panView.bottom > showImgView.height){
            panView.top = showImgView.height - panView.height;
        }
        [recognizer setTranslation:CGPointZero inView:self.view];
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled) {
        NSLog(@"FlyElephant---视图拖动结束");
    }
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
